//
//  BlogOrUserListVC.swift
//  mmda
//
//  Created by 李陆涛 on 2018/8/6.
//  Copyright © 2018年 mmda. All rights reserved.
//

import UIKit
import MJRefresh
import DZNEmptyDataSet

class BlogOrUserListVC: BaseTabVC {
    
    private var viewModel:BlogOrUserListViewModel!
    
    private weak var bigPhotoView:PictureView?
    
    /// 初始化
    ///
    /// - Parameters:
    ///   - pageType: 页面类型
    ///   - userid: 用户ID,pagetype=.auser时用,
    init(pageType: BlogOrUserListType, userid: Int? = nil) {
        
        viewModel = BlogOrUserListViewModel()
        
        viewModel.pageType = pageType
        viewModel.userid = userid
        
        super.init(style: .grouped)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        
        //        tableView.cr.removeHeader()
        //        tableView.cr.removeFooter()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupData()
    }
    
    private func setupUI() {
        
        tableView.register(UINib(nibName: "UserCell", bundle: nil), forCellReuseIdentifier: "UserCell")
        tableView.register(UINib(nibName: "BlogCell", bundle: nil), forCellReuseIdentifier: "BlogCell")
        
        tableView.estimatedRowHeight = 140;
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle = .none
        
        tableView.sectionHeaderHeight = 8.0;
        tableView.sectionFooterHeight = 0.1
        
        
        if viewModel.pageType == .auser || viewModel.pageType == .mine {
            
            tableView.tableHeaderView = userInfoHeadView()
            
            self.setCustomBarStyle(.alpha(0))
            
            
            if #available(iOS 11.0, *) {
                
                tableView.contentInsetAdjustmentBehavior = .never
            } else {
                
                self.automaticallyAdjustsScrollViewInsets = false
            }
            
        } else {
            
            tableView.tableHeaderView = placeholderHeadView()
        }
    }
    
    
    private func placeholderHeadView() -> UIView {
        
        let headview = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 8))
        headview.backgroundColor = .clear
        
        return headview
    }
    
    private var userInfoHead:UserinfoHeadView?
    
    private func userInfoHeadView() -> UIView {
        
        let headView = UserinfoHeadView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 100))
        
        headView.userHeadAction = {
            [weak self] in
            guard let `self` = self else { return }
            
            let userVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ModifyUserInfoVC") as! ModifyUserInfoVC
            userVC.user = self.viewModel.user
            userVC.pageType = 1
            
            self.navigationController?.pushViewController(userVC, animated: true)
        }
        
        
        userInfoHead = headView
        
        return headView
    }
    
    
    func setupData() {
        
        viewModel.loadUserFinished = {
            
            [weak self] error in
            guard let `self` = self else { return }
            
            if let error = error {
                
                self.showToast(error)
            }
            
            guard let user = self.viewModel.user else { return }
            
            
            self.userInfoHead!.user = user
            
            var frame = self.userInfoHead!.frame
            frame.size.height = self.userInfoHead!.viewHeight
            
            self.userInfoHead!.frame = frame
            
            self.tableView.tableHeaderView = self.userInfoHead
            
        }
        
        viewModel.loadFinished = {
            [weak self] error, isLoadMore in
            guard let `self` = self else { return }
            
            if let error = error {
                
                self.showToast(error)
            }
            
            if isLoadMore {
                
                self.tableView.mj_footer.endRefreshing()
                
            } else {
                
                self.tableView.mj_header.endRefreshing()
                self.tableView.mj_footer.resetNoMoreData()
                self.userInfoHead?.stopLoadingAnimation()
            }
            if self.viewModel.dataSource.count == 0 || self.viewModel.dataSource.count % kPerPage != 0 {
                
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            
            self.setupNoData()
            
            self.tableView.reloadData()
        }
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.viewModel.reloadData()
        })
        
        tableView.mj_footer = MJRefreshAutoFooter(refreshingBlock: {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.viewModel.getMoreData()
        })
        
        tableView.mj_header.beginRefreshing()
    }
}

extension BlogOrUserListVC {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        return viewModel.dataSource.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 1
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        if viewModel.pageType == .alluser {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell") as! UserCell
            
            let user = viewModel.dataSource[indexPath.section]
            
            cell.setUser(user as! User)
            
            return cell
            
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "BlogCell") as! BlogCell
        
        let blog = viewModel.dataSource[indexPath.section]
        
        cell.setBlog(blog as! Blog)
        
        cell.delegate = self
        
        cell.reloadCell = {
            
            [weak self] cell in
            guard let `self` = self else { return }
            
            guard let idp = tableView.indexPath(for: cell) else { return }
            
            self.tableView.beginUpdates()
            self.tableView.reloadRows(at: [idp], with: UITableViewRowAnimation.none)
            self.tableView.endUpdates()
        }
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if viewModel.pageType == .alluser {
            
            let user = viewModel.dataSource[indexPath.section] as! User
            
            let userBlogVC = BlogOrUserListVC(pageType: .auser, userid: user._id)
            
            self.navigationController?.pushViewController(userBlogVC, animated: true)
            
            return
        }
        
        let blog = viewModel.dataSource[indexPath.section] as! Blog
        
        let detailVC = BlogDetailVC(blog)
        
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
    
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        guard let headView = userInfoHead else { return }
        
        let yoffset = self.tableView.contentOffset.y
        
        let h = CGFloat(kScreenWidth) * 9 / 16
        
        if yoffset < 0 {
            
            let frame = CGRect(x: 0, y: yoffset, width: CGFloat(kScreenWidth), height: h - yoffset)
            
            headView.userBGImageView.frame = frame
        }
        
        if yoffset < -54 {
            
            headView.starLoadingAnimation()
        }
        
        if yoffset < (h - CGFloat(kNavigationBarHeight)) {
            
            let alpha = yoffset / (h - CGFloat(kNavigationBarHeight))
            
            if alpha > 0.8 {
                
                self.setCustomBarStyle(.alpha(1))
                self.title = viewModel.user?.nickname
            } else {
                
                self.setCustomBarStyle(.alpha(0))
                self.title = nil
            }
            
        }
    }
}

extension BlogOrUserListVC : BlogCellDelegagte {
    
    func blogCell(cell:BlogCell,userid:Int?) {
        
        if viewModel.pageType == .allblog {
            
            let userBlogVC = BlogOrUserListVC(pageType: .auser, userid: userid)
            
            self.navigationController?.pushViewController(userBlogVC, animated: true)
        }
    }
    
    func blogCell(cell:BlogCell, need present:UIViewController) {
        
        
//        if present.isKind(of: LLTVideoPlayerVC.self) {
//            
//            self.llt_present(present, animated: LLTTransitionAnimationType.sysCameraIrisHollowOpen)
//            
//            return
//        }
        
        self.present(present, animated: true, completion: nil)
    }
    
    func blogCell(cell:BlogCell, action:ActionType, blog:Blog) {
        
        
        if action == .map {
            
            NotificationCenter.default.post(name: kBackMapReloadNotifationName, object: nil, userInfo: [kNotifationNameObj:blog])
            self.navigationController?.popToRootViewController(animated: true)
            
            return
        }
        
        if action == .comment {
            
            if let count = blog.comment_count, count > 0 {
                
                tableView(self.tableView, didSelectRowAt: self.tableView.indexPath(for: cell)!)
                return
            }
            
            let commentVC = CommentVC()
            
            commentVC.blogid = blog._id
            
            commentVC.show(self)
            
            commentVC.commentSuccess = {
                [weak cell] comment in
                guard let `cell` = cell else { return }
                
                blog.comment_count = (blog.comment_count ?? 0) + 1
                
                cell.setBlog(blog)
            }
            
            
            return
        }
        
        
        if action == .auth {
            
            let alertVC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
            
            
            if blog.user_id == AppManager.share.user?._id {
                
                alertVC.addAction(UIAlertAction(title: "设为仅自己可见", style: .default, handler: {
                    
                    [weak self] _ in
                    guard let `self` = self else { return }
                    
                    self.changeBlogStatus(cell: cell, blog: blog, status: 11)
                }))
                
                alertVC.addAction(UIAlertAction(title: "设为所有人可见", style: .default, handler: {
                    
                    [weak self] _ in
                    guard let `self` = self else { return }
                    
                    self.changeBlogStatus(cell: cell, blog: blog, status: 0)
                }))
                
                alertVC.addAction(UIAlertAction(title: "删除", style: .destructive, handler: {
                    
                    [weak self] _ in
                    guard let `self` = self else { return }
                    
                    self.deleteBlog(cell: cell, blog: blog)
                }))
            } else {
                
                alertVC.addAction(UIAlertAction(title: "投诉", style: .default, handler: {
                    
                    [weak self] _ in
                    guard let `self` = self else { return }
                    
                    let reportVC = ReportVC(style: .plain)
                    
                    reportVC.bid = blog._id
                    
                    self.navigationController?.pushViewController(reportVC, animated: true)
                    
                }))
            }
            
            alertVC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
            
            self.present(alertVC, animated: true, completion: nil)
            
        }
    }
    
    private func changeBlogStatus(cell:BlogCell, blog:Blog, status:Int) {
        
        if blog.status != status {
            
            NetAPI.bloghide(bid: blog._id!, status: status).request {
                
                [weak self] response, errmsg in
                guard let `self` = self else { return }
                
                
                if let msg = errmsg {
                    
                    self.showToast(msg)
                    return
                }
                
                self.showToast("修改成功")
                
                blog.status = status
                
                guard let indexpath = self.tableView.indexPath(for: cell) else { return }
                
                self.tableView.reloadRows(at: [indexpath], with: UITableViewRowAnimation.automatic)
                
            }
        }
        
    }
    
    private func deleteBlog(cell:BlogCell, blog:Blog) {
        
        NetAPI.blogdelete(bid: blog._id!).request {
            
            [weak self] response, errmsg in
            guard let `self` = self else { return }
            
            
            if let msg = errmsg {
                
                self.showToast(msg)
                return
            }
            
            self.showToast("删除成功")
            
            self.viewModel.dataSource.remove(blog)
            
            guard let indexpath = self.tableView.indexPath(for: cell) else { return }
            
            self.tableView.deleteSections([indexpath.section], with: UITableViewRowAnimation.automatic)
            
        }
    }
}

extension BlogOrUserListVC: DZNEmptyDataSetSource,DZNEmptyDataSetDelegate {
    
    func setupNoData() {
        
        self.tableView.emptyDataSetSource = self
        self.tableView.emptyDataSetDelegate = self
    }
    
    func verticalOffset(forEmptyDataSet scrollView: UIScrollView!) -> CGFloat {
        
        
        if viewModel.pageType == .auser || viewModel.pageType == .mine {
            
            return 120;
        }
        
        return 0;
        
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        
        return #imageLiteral(resourceName: "暂无数据")
    }
    
    func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        
        return NSAttributedString(string: "该用户还未发表过动态", attributes:[NSAttributedStringKey.font:kFont14!,NSAttributedStringKey.foregroundColor:UIColor.black.withAlphaComponent(0.3)])
    }
}


